import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';
import moment from 'moment';
import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { Button, message } from 'antd';

import '@ant-design/compatible/assets/index.css';

import BasicInfoElem from './components/BasicInfoElem';
import HardwareProductElem from './components/HardwareProductElem';
import SalesDetailElem from './components/SalesDetailElem';
import BorrowingInfoElem from './components/BorrowingInfoElem';
import AccountInfoElem from './components/AccountInfoElem';
import SettlementElem from './components/SettlementElem';

interface AddInfoProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  detail: any;
  contractTypeDetail: any;
  location: { query: { id: number; type: number } };
}

interface AddInfoState {
  selectContract: number;
  initialValues: any;
  formValues: object;
}

function mapStateToProps(state: any) {
  const {
    franchiseeContractEditor: { detail, contractTypeDetail },
  } = state;

  return {
    detail,
    contractTypeDetail,
  };
}

@connect(mapStateToProps)

class AddInfo extends Component<AddInfoProps, AddInfoState> {
  state: AddInfoState = {
    selectContract: 1, // 用于判断合同类型
    initialValues: {}, // 初始值(回显信息)
    formValues: {}, // 提交表单
  };

  static getDerivedStateFromProps(nextProps: AddInfoProps, preState: AddInfoState) {
    const { detail } = nextProps;
    const { initialValues } = preState;

    if (!Object.is(detail, initialValues)) {
      return ({ initialValues: { ...detail } });
    }

    return null;
  }

  componentDidMount() {
    const {
      location: { query: { id, type } },
    } = this.props;

    if (id && type) this.setDataInfo(id, type);

    this.fetchAction('common/fetchAddressList');
    this.fetchAction('fetchPartners');
    this.fetchAction('common/fetchAddressList');
  }

  componentDidUpdate(prevProps: any) {
    const { location: { query: { id, type } } } = this.props;
    if (id && type && (id !== prevProps.location.query.id
      || type !== prevProps.location.query.type
    )) {
      this.setDataInfo(id, type);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear', null);
  }

  // 设置type并请求数据
  setDataInfo = (id: number, type: any) => {
    this.setState({
      selectContract: Number(type),
    }, () => {
      this.fetchDetailInfo({ id, type });
      this.mergeChildToParent('id', id);
    });
  }

  fetchDetailInfo = (params: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'franchiseeContractEditor/fetch',
      payload: params,
    });
  }

  // 选择合同类型
  selectcontractType = (selectContract: number) => this.setState({ selectContract });

  // 合并请求参数
  mergeChildToParent = (name: string, value: any) => {
    const { formValues } = this.state;
    formValues[name] = value;

    this.setState({ formValues });
  }

  settingSettlement = () => (
    {
      party_a_acc_bank: '',
      party_b_acc_bank: '',
      delivery_service_fee: 1,
      sending_service_fee: 1,
      deposit_service_fee: 1,
      sms_service_fee: 1,
      withdraw_charge_ratio: 1,
      service_fee_type: 2,
      settle_type: 1,
    }
  )

  togglePriceType = (origin: any) => {
    const { initialValues }: any = this.state;
    let new_origin = {};
    if (origin.contract_type === 1) {
      new_origin = {
        reserve_list: '[]',
        ...origin,
        delivery_service_fee: Math.round(Number(origin.delivery_service_fee) * 100),
        deposit_service_fee: Math.round(Number(origin.deposit_service_fee) * 100),
        sending_service_fee: Math.round(Number(origin.sending_service_fee) * 100),
        sms_service_fee: Math.round(Number(origin.sms_service_fee) * 100),
        send_income_ratio: Math.round(Number(origin.send_income_ratio)),
        delivery_delay_fee_ratio: Number(origin.delivery_delay_fee_ratio),
        withdraw_charge_ratio: Number(origin.withdraw_charge_ratio),
      };
    } else if (origin.contract_type === 2) {
      const { detail_list } = origin;
      const new_detail_list = JSON.parse(detail_list).map((item: any) => {
        item = {
          ...item,
          unit_price: item.unit_price * 100,
          total_price: item.total_price * 100,
        };
        return item;
      });

      new_origin = {
        ...origin,
        detail_list: JSON.stringify(new_detail_list),
      };
    } else {
      return {
        repayment_count: initialValues.repayment_count,
        ...origin,
        down_payment: Number(origin.down_payment) * 100,
        loan_amount: Number(origin.loan_amount) * 100,
      };
    }

    return new_origin;
  };

  // 提交表单
  handleSubmit = (status: any) => {
    const { formValues } = this.state;
    const {
      form: { validateFieldsAndScroll },
      detail,
    } = this.props;

    validateFieldsAndScroll((errors: any, values: any) => {
      if (errors) return;
      const sum = parseInt(values.advance_percent, 10)
      + parseInt(values.deliver_percent, 10)
      + parseInt(values.final_percent, 10);

      if (values.contract_type === 2 && sum !== 100) {
        message.error('预付款、发货款和尾款比例之和需为100!');
      } else {
        if (values.momentTime) {
          values.start_time = moment(values.momentTime[0]).format('YYYY-MM-DD');
          values.end_time = moment(values.momentTime[1]).format('YYYY-MM-DD');

          delete values.momentTime;
          delete values.modelType;
        }
        if (typeof values.franchise_region === 'object') {
          values.franchise_region = `${values.franchise_region[0]}#${values.franchise_region[1]}#${values.franchise_region[2]}
            `.replace(/\s+/g, '');
        }

        let params = {
          status,
          ...(this.settingSettlement()),
          ...values,
          ...formValues,
        };

        if (params.delivery_delay_fee_ratio > 100) {
          message.error('延期费抽成比例范围是：0 -- 100');
          return;
        }

        if (params.delivery_delay_fee_ratio < 0) {
          message.error('延期费抽成比例范围是：0 -- 100');
          return;
        }

        if (params.contract_type === 3 && !params.repayment_count && !detail.repayment_count) {
          message.error('请先生成还款明细!');
          return;
        }

        params = this.togglePriceType(params);
        const { settle_amount, settle_type } = params;
        let new_settle_amount = 0;
        if (settle_amount) {
          if (settle_type !== 2) {
            const addSettle_amount: any = settle_amount * 100;
            new_settle_amount = parseInt(addSettle_amount, 10);
          } else {
            new_settle_amount = settle_amount;
          }
        } else {
          new_settle_amount = 0;
        }
        // eslint-disable-next-line radix
        params.delivery_delay_fee_ratio = parseInt(`${params.delivery_delay_fee_ratio * 100}`);

        params = {
          ...params,
          settle_amount: new_settle_amount,
        };

        this.fetchAction('add', params);
      }
    });
  };

  // action请求
  fetchAction(typeName: string, payload: any = {}) {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName
      : `franchiseeContractEditor/${typeName}`;
    dispatch({
      type,
      payload,
    });
  }

  render() {
    const {
      form,
      location: { query },
      contractTypeDetail,
    } = this.props;

    const { selectContract } = this.state;
    const type = query.type || selectContract;
    const id = query.id || '';

    const is_exclusive = contractTypeDetail.fcs_info
      ? contractTypeDetail.fcs_info.region_info.is_exclusive
      : 1;

    return (
      <Fragment>
        <PageHeader />
        <Form hideRequiredMark className="tableListForm">
          <BasicInfoElem
            contractType={Number(type)}
            contractId={id}
            forms={form}
            selectContractType={this.selectcontractType.bind(this)}
            fetchAction={this.fetchAction.bind(this)}
            mergeFun={this.mergeChildToParent}
          />
          {
            selectContract === 1 && (
              <Fragment>
                {is_exclusive === 1 && (
                  <HardwareProductElem forms={form} mergeFun={this.mergeChildToParent} />
                )}
                <AccountInfoElem forms={form} />
                <SettlementElem forms={form} mergeFun={this.mergeChildToParent} />
              </Fragment>
            )
          }
          {
            selectContract === 2 && (
              <SalesDetailElem forms={form} mergeFun={this.mergeChildToParent} />
            )
          }
          {
            selectContract === 3 && (
              <BorrowingInfoElem
                forms={form}
                fetchAction={this.fetchAction.bind(this)}
                mergeFun={this.mergeChildToParent}
              />
            )
          }
          <div
            style={{
              width: '100%',
              background: '#fff',
              paddingBottom: 20,
              paddingLeft: 20,
            }}
          >
            <Button
              type="primary"
              className="marginR16"
              onClick={() => this.handleSubmit(1)}
            >
              提交
            </Button>

            <Button
              type="primary"
              className="submitSave marginR16"
              onClick={() => this.handleSubmit(3)}
            >
              保存
            </Button>

            <Button
              ghost
              type="primary"
              onClick={() => router.goBack()}
            >
              取消
            </Button>
          </div>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<AddInfoProps>()(AddInfo);
